package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
//@Transactional  暂时先别管事务
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;

    @Autowired
    private MongoTemplate template;



    //page对象里面包括: 总页数 每页显示条数......
    public Page<Region> query(RegionQuery qo) {
        //创建Query对象,根据过滤条件查询总条数,此处没有限制条件,所以用空的查询对象查
        Query query = new Query();
        //有数据,进行分页操作,创建新的分页对象,此索引从0开始,所以要减一,分页的字段与数据库一致
        Pageable pageAble = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        //返回给控制器
        return DBHelper.query(template, Region.class, query, pageAble);
    }



    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void save(Region region) {
        //调用MongoDB的repository进行保存
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void changeHotById(Integer hot, String id) {
        //调用update方法,此时需要先查再改
        Region region = repository.findById(id).get();
        int i = hot == 1 ? 0 : 1;
        region.setIshot(hot);

        repository.save(region);
    }

    @Override
    public void deleteById(String id) {
        repository.deleteById(id);
    }

}
